package com.chengyu.core.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONArray;
import com.chengyu.core.component.OperationLog;
import com.chengyu.core.domain.form.CaculateFreightFeeForm;
import com.chengyu.core.domain.form.OrderAddForm;
import com.chengyu.core.domain.form.OrderBuyDetailForm;
import com.chengyu.core.domain.form.PayBaseForm;
import com.chengyu.core.domain.result.OrderPayResult;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.model.*;
import com.chengyu.core.service.goods.GoodsService;
import com.chengyu.core.service.member.MemberCouponService;
import com.chengyu.core.service.member.MemberRechargeService;
import com.chengyu.core.service.order.OrderGroupService;
import com.chengyu.core.service.order.OrderService;
import com.chengyu.core.service.pay.PayService;
import com.chengyu.core.service.pay.TyPayService;
import com.chengyu.core.service.ty.TyOrderService;
import com.chengyu.core.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "订单")
@Controller
@RequestMapping("/member")
public class PayController extends UserBaseController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private TyPayService tyPayService;

	@Autowired
	private MemberRechargeService rechargeService;

	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OrderGroupService orderGroupService;
	@Autowired
	private MemberCouponService memberCouponService;
	@Autowired
	private PayService payService;



	@OperationLog
	@ApiOperation(value = "支付订单")
	@ResponseBody
	@RequestMapping(value={"/pay"}, method=RequestMethod.POST)
	public CommonResult<Map<String,Object>> payOrder(String orderGroup,String payOrderNo, PayBaseForm payBaseForm,
													 Integer memberId, BigDecimal amount, String orderNo
	) throws Exception{
		UmsMember member = getCurrentMember();
		super.validateRepeat("payOrder-"+member.getId(), 5000L, "点太快了,请等待5秒再尝试~");

		payBaseForm.setIp(this.getRequestIp());
		String message = "";


		System.out.println("orderGroup:"+orderGroup);
		System.out.println("amount:"+amount);
		System.out.println("payOrderNo:"+payOrderNo);
		System.out.println("payBaseForm:"+payBaseForm.toString());
//		订单:order;订单:tyOrder;充值:recharge;红包:redbag;保障:bazhang;
		switch (orderGroup) {
			case  "order":
				System.out.println("orderorderorderorderorder");
				//调用支付接口
				if(payOrderNo!=null) {
					message = payService.orderPay(member, payOrderNo, payBaseForm);
				}
				break;
			case  "tyOrder":
				System.out.println("tyOrdertyOrdertyOrdertyOrdertyOrder");
				if(payOrderNo!=null) {
					message = tyPayService.orderPay(member, payOrderNo, payBaseForm);
				}
				break;
			case  "tyOrderAdd":
				System.out.println("tyOrdertyOrdertyOrdertyOrdertyOrder_addmoney");
				if(payOrderNo!=null) {
					message = tyPayService.addPay(member, orderNo, amount,payBaseForm);
				}
				break;
			case  "bzj":
				System.out.println("bzjbzjbzjbzjbzjbzj");
				if(amount!=null){
					return  bzj( payBaseForm, amount);
				}
				break;
			case  "recharge":
				System.out.println("rechargerechargerechargerechargerecharge");
				if(amount!=null){
					return   recharge( payBaseForm, amount);
				}
				break;
			case  "redbag":
				System.out.println("redbagredbagredbagredbag");
				if(amount!=null&& memberId!=null){
					return   redbag( payBaseForm, amount,memberId  );
				}
				break;
			default:
				break;

		}

//		{
//			"code": 500,
//				"message": "\n### Error updating database.  Cause: java.sql.SQLException: Field 'paymethod' doesn't have a default value\n### The error may exist in URL" +
//				" [jar:file:/www/wwwroot/ccchongya.com/petshop-portal-1.0-SNAPSHOT.jar!/BOOT-INF/lib/petshop-service-1.0-SNAPSHOT.jar!/com/chengyu/core/mapper/UmsMemberRechargeMapper.xml]" +
//				"\n### The error may involve com.chengyu.core.mapper.UmsMemberRechargeMapper.insertSelective-Inline\n### The error occurred while setting parameters\n### SQL: " +
//				"insert into ums_member_recharge      ( order_no,                       member_id,                       from_member_id,                        member_name,                            " +
//				"                amount,                       real_amount,                                                   save_time,                                     status,                     " +
//				"         add_time )     " +
//				"  values ( ?,                       ?,                       ?,                       ?,                                            ?,                       ?,      " +
//				"                                             ?,                                     ?,                              ? )" +
//				"\n### Cause: java.sql.SQLException: Field 'paymethod' doesn't have a default value\n; Field 'paymethod' doesn't have a default value; nested exception is java.sql.SQLException: Field 'paymethod' doesn't have a default value"
//		}

		Map<String,Object> result = new HashMap<>();
		result.put("payOrderNo", payOrderNo);
		result.put("message", message);
		return CommonResult.success(result);
	}


//"message": "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2021004129657282&biz_content=%7B%22body%22%3A%22%E8%AE%A2%E5%8D%95%22%2C%22out_trade_no%22%3A%22R1710329455873342%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%E5%85%85%E5%80%BC-R1710329455873342%22%2C%22total_amount%22%3A%225.00%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=https%3A%2F%2Fapi.ccchongya.com%2Fcommon%2FaliPay%2Fcallback&sign=LZ%2FYJAdh%2BKI0bL33cMeGsuPHZeVHwgXQjdO6HFS09lJRhUa1QCOKC6GgBvVwEH2mieTeoYtmmq78LjdgO3uOZTiAch9jhLRjS90T5B1UCoVlXT01nmZ1aX8EpqSprKViy8dY18LsNhmQxnQG7J955lBdhnM4%2FvLS3BFIMv4oMrpNFoSSUVWd6x%2Bb%2BFJtZtrC6tIX2TkT8wbY1jkYksOM6IljVcoUOAmxq1AgNz4rEEJ92tytiU1dC2MQCwU8aMw%2BbHFkR7hONSl0Qful2YN9pDhQHbcSJf1Fed8CR99qI7ai87qaQQ2NyUlYZExoF%2F4zIHlMuerpGmpUH4TBh3RYEw%3D%3D&sign_type=RSA2&timestamp=2024-03-13+19%3A30%3A55&version=1.0"
//
	public CommonResult<Map<String,Object>> redbag(PayBaseForm payBaseForm, BigDecimal amount,Integer memberId) throws Exception {
		if(amount.compareTo(BigDecimal.ZERO) <= 0){
			throw new ServiceException("member.recharge.amount");
		}


		String payMethod  =  payBaseForm.getPayMethod();
//		ArrayList<String> arrayList = new ArrayList<String>();
//		arrayList.add("aliPay");
//		arrayList.add("wxPay");
//		arrayList.contains(payMethod);
		System.out.println("payMethod");
		System.out.println(payMethod);
		if(!CollectionUtil.contains(CollectionUtil.newArrayList("aliPay","wxPay"),payMethod)){
			throw new ServiceException("数据错误！");
		}


		UmsMember member =  memberService.getById(memberId);
		UmsMember fromMember = getCurrentMember();



		super.validateRepeat("do-recharge-time-between-" + member.getId(), 5000L, "platform.validate.repeat");
		String orderNo = rechargeService.redbag(member, payBaseForm.getPayMethod(), amount,fromMember);

		//调用支付接口
		payBaseForm.setIp(this.getRequestIp());

		String message = payService.redbag(member, orderNo, payBaseForm,fromMember);

		Map<String,Object> result = new HashMap<>();
		result.put("payOrderNo", orderNo);
		result.put("message", message);
		return CommonResult.success(result);
	}





	//	"在线充值"
	public CommonResult<Map<String,Object>> recharge(PayBaseForm payBaseForm, BigDecimal amount) throws Exception {


		System.out.println("rechargerechargerechargerechargerechargerecharge");


		if(amount.compareTo(BigDecimal.ZERO) <= 0){
			throw new ServiceException("member.recharge.amount");
		}
		String payMethod  =  payBaseForm.getPayMethod();
//		ArrayList<String> arrayList = new ArrayList<String>();
//		arrayList.add("aliPay");
//		arrayList.add("wxPay");
//		arrayList.contains(payMethod);
		System.out.println("payMethod");
		System.out.println(payMethod);
		if(!CollectionUtil.contains(CollectionUtil.newArrayList("aliPay","wxPay"),payMethod)){
			throw new ServiceException("数据错误！");
		}


		UmsMember member = getCurrentMember();
		super.validateRepeat("do-recharge-time-between-" + member.getId(), 5000L, "platform.validate.repeat");
		String orderNo = rechargeService.rechargeOnline(member, payBaseForm.getPayMethod(), amount);

		//调用支付接口
		payBaseForm.setIp(this.getRequestIp());
		String message = payService.recharge(member, orderNo, payBaseForm);

		Map<String,Object> result = new HashMap<>();
		result.put("payOrderNo", orderNo);
		result.put("message", message);

		return CommonResult.success(result);
	}


	//	"在线充值"
	public CommonResult<Map<String,Object>> bzj(PayBaseForm payBaseForm, BigDecimal amount) throws Exception {

		System.out.println("bzjbzjbzjbzjbzjbzj");
		if(amount.compareTo(BigDecimal.ZERO) <= 0){
			throw new ServiceException("member.recharge.amount");
		}
		String payMethod  =  payBaseForm.getPayMethod();
//		ArrayList<String> arrayList = new ArrayList<String>();
//		arrayList.add("aliPay");
//		arrayList.add("wxPay");
//		arrayList.contains(payMethod);

//		if(!CollectionUtil.contains(CollectionUtil.newArrayList("aliPay","wxPay"),payMethod)){
//			throw new ServiceException("数据错误！");
//
//		}


		UmsMember member = getCurrentMember();
		super.validateRepeat("do-recharge-time-between-" + member.getId(), 5000L, "platform.validate.repeat");
		String orderNo = rechargeService.bzj(member, payBaseForm.getPayMethod(), amount);

		//调用支付接口
		payBaseForm.setIp(this.getRequestIp());
		String message = payService.bzj(member, orderNo, payBaseForm);

		Map<String,Object> result = new HashMap<>();
		result.put("payOrderNo", orderNo);
		result.put("message", message);
		return CommonResult.success(result);
	}




//	@ApiOperation(value = "支付详情")
//	@ApiImplicitParams({
//		@ApiImplicitParam(name = "payOrderNo", value = "支付订单号"),
//	})
//	@ResponseBody
//	@RequestMapping(value="/order/payDetail", method=RequestMethod.GET)
//	public CommonResult<OmsPayOrder> payDetail(String payOrderNo) throws Exception{
//		OmsPayOrder payOrder = orderService.getPayOrder(payOrderNo);
//		return CommonResult.success(payOrder);
//	}

}
